import { ref, computed, readonly } from 'vue'
import { Card } from '../types/card'
import { validateCards } from '../utils/validation'
import { identifyCardPattern } from '../utils/gameLogic'

/**
 * 扑克牌选择管理组合式函数
 */
export function useCardSelection() {
  // 响应式数据
  const selectedCards = ref<Card[]>([])
  const selectionMode = ref<'single' | 'multiple'>('multiple')
  const maxSelection = ref<number>(0) // 0表示无限制

  /**
   * 选择扑克牌
   */
  const selectCard = (card: Card) => {
    try {
      if (selectionMode.value === 'single') {
        // 单选模式：替换当前选择
        selectedCards.value = [card]
      } else {
        // 多选模式：切换选择状态
        const index = selectedCards.value.findIndex(c => c.id === card.id)
        if (index >= 0) {
          // 已选中，取消选择
          selectedCards.value.splice(index, 1)
        } else {
          // 未选中，添加选择
          if (maxSelection.value > 0 && selectedCards.value.length >= maxSelection.value) {
            throw new Error(`最多只能选择${maxSelection.value}张牌`)
          }
          selectedCards.value.push(card)
        }
      }
    } catch (error) {
      console.error('选择扑克牌失败:', error)
      throw error
    }
  }

  /**
   * 批量选择扑克牌
   */
  const selectCards = (cards: Card[]) => {
    try {
      validateCards(cards)

      if (selectionMode.value === 'single' && cards.length > 1) {
        throw new Error('单选模式下只能选择一张牌')
      }

      if (maxSelection.value > 0 && cards.length > maxSelection.value) {
        throw new Error(`最多只能选择${maxSelection.value}张牌`)
      }

      selectedCards.value = [...cards]
    } catch (error) {
      console.error('批量选择扑克牌失败:', error)
      throw error
    }
  }

  /**
   * 取消选择指定扑克牌
   */
  const deselectCard = (card: Card) => {
    const index = selectedCards.value.findIndex(c => c.id === card.id)
    if (index >= 0) {
      selectedCards.value.splice(index, 1)
    }
  }

  /**
   * 清空选择
   */
  const clearSelection = () => {
    selectedCards.value = []
  }

  /**
   * 检查扑克牌是否被选中
   */
  const isCardSelected = (card: Card): boolean => {
    return selectedCards.value.some(c => c.id === card.id)
  }

  /**
   * 设置选择模式
   */
  const setSelectionMode = (mode: 'single' | 'multiple') => {
    selectionMode.value = mode

    // 如果切换到单选模式且当前选择了多张牌，只保留第一张
    if (mode === 'single' && selectedCards.value.length > 1) {
      selectedCards.value = selectedCards.value.slice(0, 1)
    }
  }

  /**
   * 设置最大选择数量
   */
  const setMaxSelection = (max: number) => {
    maxSelection.value = max

    // 如果当前选择超过限制，截断到限制数量
    if (max > 0 && selectedCards.value.length > max) {
      selectedCards.value = selectedCards.value.slice(0, max)
    }
  }

  /**
   * 验证当前选择
   */
  const validateSelection = (): boolean => {
    try {
      if (selectedCards.value.length === 0) {
        return true // 空选择是合法的（过牌）
      }

      validateCards(selectedCards.value)

      // 验证牌型
      const combination = identifyCardPattern(selectedCards.value)
      return combination.type !== undefined

    } catch (error) {
      console.error('选择验证失败:', error)
      return false
    }
  }

  /**
   * 获取选择的牌型信息
   */
  const getSelectionInfo = computed(() => {
    if (selectedCards.value.length === 0) {
      return {
        count: 0,
        combination: null,
        isValid: true
      }
    }

    try {
      const combination = identifyCardPattern(selectedCards.value)
      return {
        count: selectedCards.value.length,
        combination,
        isValid: validateSelection()
      }
    } catch (error) {
      return {
        count: selectedCards.value.length,
        combination: null,
        isValid: false
      }
    }
  })

  /**
   * 检查是否可以添加更多牌
   */
  const canSelectMore = computed(() => {
    if (selectionMode.value === 'single') {
      return selectedCards.value.length === 0
    }

    if (maxSelection.value > 0) {
      return selectedCards.value.length < maxSelection.value
    }

    return true
  })

  /**
   * 获取选择状态摘要
   */
  const selectionSummary = computed(() => {
    const info = getSelectionInfo.value
    return {
      count: info.count,
      mode: selectionMode.value,
      maxSelection: maxSelection.value,
      isValid: info.isValid,
      canSelectMore: canSelectMore.value,
      combinationType: info.combination?.type,
      combinationPower: info.combination?.power
    }
  })

  return {
    // 状态
    selectedCards: readonly(selectedCards),
    selectionMode: readonly(selectionMode),
    maxSelection: readonly(maxSelection),

    // 计算属性
    getSelectionInfo,
    canSelectMore,
    selectionSummary,

    // 方法
    selectCard,
    selectCards,
    deselectCard,
    clearSelection,
    isCardSelected,
    setSelectionMode,
    setMaxSelection,
    validateSelection
  }
}